package com.whf.android.jar.net.download;

import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.whf.android.jar.app.Latte;
import com.whf.android.jar.net.HttpCode;
import com.whf.android.jar.net.RestCreator;
import com.whf.android.jar.net.callback.IError;
import com.whf.android.jar.net.callback.IFailure;
import com.whf.android.jar.net.callback.IRequest;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.util.log.LatteLogger;

import java.util.WeakHashMap;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 下载
 *
 * @author 傅令杰
 * @version 2017/4/2
 */
public final class DownloadLangHandler {

    private final String URL;
    //加密等请求头
    private final WeakHashMap<String, Object> HEADERS;
    /// 参数
    private final WeakHashMap<String, Object> PARAMS;
    private final IRequest REQUEST;
    private final String DOWNLOAD_DIR;
    private final String EXTENSION;
    private final String NAME;
    private final ISuccess SUCCESS;
    private final IFailure FAILURE;
    private final IError ERROR;

    public DownloadLangHandler(String url,
                               WeakHashMap<String, Object> headers,
                               WeakHashMap<String, Object> params,
                               IRequest request,
                               String downDir,
                               String extension,
                               String name,
                               ISuccess success,
                               IFailure failure,
                               IError error) {
        this.URL = url;
        this.HEADERS = headers;
        this.PARAMS = params;
        this.REQUEST = request;
        this.DOWNLOAD_DIR = downDir;
        this.EXTENSION = extension;
        this.NAME = name;
        this.SUCCESS = success;
        this.FAILURE = failure;
        this.ERROR = error;
    }

    public final void handleDownload() {
        if (REQUEST != null) {
            REQUEST.onRequestStart();
        }
        RestCreator.getDownloadRestService()
                .downloadLang(HEADERS, URL, PARAMS)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    public void onResponse(@NonNull Call<ResponseBody> call,
                                           @NonNull Response<ResponseBody> response) {
                        if (response.isSuccessful()) {
                            final ResponseBody responseBody = response.body();
                            if (responseBody != null) {
                                final SaveFileTask task = new SaveFileTask(REQUEST, SUCCESS, ERROR, responseBody,
                                        DOWNLOAD_DIR, EXTENSION, NAME);
                                task.executeOnExecutor();
                            } else {
                                handleError(HttpCode.CODE__1, "Response body is null");
                            }
                        } else {
                            handleError(response.code(), response.message());
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        Latte.getHandler().post(() -> {
                            if (FAILURE != null) {
                                FAILURE.onFailure();
                            }
                            if (REQUEST != null) {
                                REQUEST.onRequestEnd();
                            }
                        });
                    }
                });
    }

    /**
     * 错误处理
     *
     * @param code         错误码
     * @param errorMessage 错误信息
     */
    private void handleError(int code, String errorMessage) {
        LatteLogger.e(errorMessage);
        Latte.getHandler().post(() -> {
            if (ERROR != null) {
                ERROR.onError(code, errorMessage);
            }
            if (REQUEST != null) {
                REQUEST.onRequestEnd();
            }
        });
    }
}
